<script setup lang="ts">
import { ref } from 'vue'
import { Lock, User } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/modules/user.ts'
import { useRouter } from 'vue-router'
import { ElNotification } from 'element-plus'
import { getTime } from '@/utils/time.ts'

const loginForm = ref({
  username: 'admin',
  password: '111111',
})
// 按钮加载状态
const loading = ref(false)
// 获取路由器
const $router = useRouter()

// 获取表单 DOM
const loginForms = ref()

// 登录按钮逻辑
const userStore = useUserStore()
const login = async () => {
  // 判断用户名和密码是否全部通过校验规则
  const checkSuccess = await loginForms.value.validate()
  // 只有全部通过，才会发送请求
  if (checkSuccess) {
    // 登录按钮显示加载效果
    loading.value = true
    /*
     * 点击登录按钮后干什么
     * 1. 通知仓库发送请求
     * 2. 请求成功 -> 跳转页面，给出登录成功提示
     * 3. 登录失败 -> 弹出登录失败信息
     * */
    try {
      // 登录成功
      await userStore.userLogin(loginForm.value)
      $router.push('/')
      // 登录成功提示
      ElNotification({
        type: 'success',
        message: '欢迎回来',
        title: `Hi ${getTime()}好`,
      })
      // 取消按钮加载效果(要等请求结束之后再改变loading状态，要不然来不及显示)
      loading.value = false
    } catch (error) {
      // 取消按钮加载效果
      loading.value = false
      ElNotification({
        type: 'error',
        message: (error as Error).message,
      })
    }
  }
}

// 自定义用户名校验规则
const validatorUsername = (rule: any, value: any, callback: any) => {
  /*
   * rule: 校验规则对象
   * value: 要校验的值
   * callback函数：如果符合规则，则放行；否则callback方法注入错误提示信息
   * */
  // 可以在此处定义正则来校验
  if (value.length >= 5 && value.length <= 10) {
    callback()
  } else {
    callback(new Error('账号长度至少为5位'))
  }
}
// 自定义密码校验规则
const validatorPassword = (rule: any, value: any, callback: any) => {
  if (value.length >= 6 && value.length <= 15) {
    callback()
  } else {
    callback(new Error('密码至少为6位'))
  }
}

// 定义用户名和密码校验规则
const rules = ref({
  username: [{ trigger: 'change', validator: validatorUsername }],
  password: [{ trigger: 'change', validator: validatorPassword }],
})
</script>

<template>
  <div class="login_container">
    <!-- 一行两列布局 -->
    <el-row>
      <!-- 当页面宽度小于768时，左侧盒子消失-->
      <el-col :span="12" :xs="0"></el-col>
      <el-col :span="12" :xs="24">
        <el-form
          ref="loginForms"
          :rules="rules"
          :model="loginForm"
          class="login_form"
        >
          <h1>Hello</h1>
          <h2>欢迎来到硅谷甄选</h2>
          <el-form-item prop="username">
            <el-input :prefix-icon="User" v-model="loginForm.username" />
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              :prefix-icon="Lock"
              v-model="loginForm.password"
              type="password"
              show-password
            />
          </el-form-item>
          <el-form-item>
            <el-button
              :loading="loading"
              @click="login"
              class="login_btn"
              type="primary"
              size="default"
            >
              登录
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped lang="scss">
.login_container {
  width: 100%;
  height: 100vh;
  background: url('@/assets/images/background.jpg') no-repeat;
  // 背景图覆盖整个盒子
  background-size: cover;

  .login_form {
    position: relative;
    width: 80%;
    top: 30vh;
    background: url('@/assets/images/login_form.png') no-repeat;
    background-size: cover;
    padding: 40px;
    h1 {
      font-size: 40px;
      color: #fff;
    }
    h2 {
      font-size: 20px;
      color: #fff;
      margin: 20px 0;
    }
    .login_btn {
      width: 100%;
    }
  }
}
</style>
